package com.lei.wiki.service.impl;

import com.lei.wiki.domain.Ebook;
import com.lei.wiki.domain.EbookExample;
import com.lei.wiki.mapper.EbookMapper;
import com.lei.wiki.req.EbookQueryReq;
import com.lei.wiki.resp.EbookQueryResp;
import com.lei.wiki.service.EbookService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lei Tao
 */
@Service
public class EbookServiceImpl implements EbookService {
    private final EbookMapper ebookMapper;

    public EbookServiceImpl(EbookMapper ebookMapper) {
        this.ebookMapper = ebookMapper;
    }

    @Override
    public List<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        criteria.andNameLike("%" + req.getName() + "%");
        List<Ebook> ebooks = ebookMapper.selectByExample(ebookExample);
        return ebooksToEbookQueryRespList(ebooks);
    }

    private List<EbookQueryResp> ebooksToEbookQueryRespList(List<Ebook> ebooks) {
        return ebooks.stream().map(ebook -> {
            EbookQueryResp ebookQueryResp = new EbookQueryResp();
            BeanUtils.copyProperties(ebook, ebookQueryResp);
            return ebookQueryResp;
        }).collect(Collectors.toList());
    }
}
